package com.sayi.dzapi.interceptor;


import org.springframework.context.annotation.Bean;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.HashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    private static final Logger log = LogManager.getLogger(GlobalInterceptor.class);

    
    RestTemplate restTemplate = new RestTemplate();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            // 获取请求URL
            String requestURL = request.getRequestURL().toString();
            // 获取请求路由
            String requestURI = request.getRequestURI();
            // 获取请求方法
            String requestMethod = request.getMethod();
            // 获取请求参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, String> params = convertParameterMapToStringMap(parameterMap);


            // 获取请求头信息
            String userAgent = request.getHeader("User-Agent");
            // 获取客户端IP地址
            String clientIp = getClientIp(request);

            /*log.info("requesturl:"+requestURL
                +",requestUri:"+requestURI
                +",requestmethod:"+requestMethod
                +",paravalue:"+params
                +",userAgent:"+userAgent
                +",clientIP:"+clientIp
            );*/

            try{
                //在这里把数据向api/send转发，用于统计
                //统计代码开始
                Map<String, Object> eventRequest = new HashMap<>();
                Map<String, Object> payload = new HashMap<>();
                //Map<String, String> data = new HashMap<>();

                //data.put("fake", "暂时不知道用来干嘛");
                //payload.put("data", data);
                payload.put("hostname", "api.lty.fan");
                payload.put("language", "zh-CN");
                //payload.put("referrer", "");
                //payload.put("screen", "1920x1080");
                //payload.put("title", "dashboard");
                payload.put("url", requestURI);
                payload.put("website", "8b219a5f-181e-48ce-a1d4-920fa8277393");
                payload.put("name", "apicall");

                eventRequest.put("payload", payload);
                eventRequest.put("type", "event");

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("User-Agent",userAgent);

                HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(eventRequest, headers);
                //log.info(requestEntity.toString());

                String url = "https://lty.fan/api/send"; // Replace with your target URL
                ResponseEntity<String> res = restTemplate.postForEntity(url, requestEntity, String.class);
                //在这里处理返回，不过似乎没什么需要处理的
                //log.info("Response status code: {}", res.getStatusCodeValue());
                //log.info("Response body: {}", res.getBody());

            //统计代码结束
            }catch(Exception e){
                //log.error(e.getMessage());
            }
        }
        return true;
    }
    private static String getClientIp(HttpServletRequest request) {
        String clientIp = request.getRemoteAddr();
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null) {
            clientIp = xForwardedFor.split(",")[0].trim();
        }
        return clientIp;
    }
    private Map<String, String> convertParameterMapToStringMap(Map<String, String[]> parameterMap) {
        Map<String, String> stringMap = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            // Assuming single value for simplicity. For multiple values, you might want to join them.
            String value = entry.getValue() != null && entry.getValue().length > 0 ? entry.getValue()[0] : "";
            stringMap.put(key, value);
        }
        return stringMap;
    }
}